package com.xbh.wificonfiglib.util;

import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.socket.client.impl.client.PulseManager;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;

/**
 * Create by LuoWen on 2020/11/17 15:53
 */
public class TcpAction {
    public static final String TAG = TcpAction.class.getSimpleName();

    private ConnectionInfo connectionInfo;
    private IConnectionManager connectionManager;

    public TcpAction(String service, int port){
        connectionInfo    = new ConnectionInfo(service, port);
    }
    public OkSocketOptions toOpenSocket(){
        //调用OkSocket,开启这次连接的通道
        connectionManager = OkSocket.open(connectionInfo);
        return connectionManager.getOption();
    }

    public void toConnect(SocketActionAdapter listener){
        toConnect(null, listener);
    }

    public void toConnect(OkSocketOptions options, SocketActionAdapter listener){
        if(connectionManager == null){
            return;
        }
        connectionManager.registerReceiver(listener);

        if(options != null){
            connectionManager.option(options);
        }
        //调用通道进行连接
        connectionManager.connect();
    }

    public void toDisconnect(OkSocketOptions options, SocketActionAdapter listener){
        if(connectionManager == null){
            return;
        }
        connectionManager.registerReceiver(listener);
        //调用通道进行连接
        if(!connectionManager.isDisconnecting()) {
            connectionManager.disconnect();
        }
    }

    public void sendMsg(ISendable sendObj){
        if(sendObj == null || connectionManager == null){
            return;
        }
        connectionManager.send(sendObj);
    }

    //手动触发一次心跳(主要用于一些需要手动控制触发时机的场景)
    public void toBeatManual(){
        if(connectionManager != null){
            PulseManager pulseManager = connectionManager.getPulseManager();
            pulseManager.trigger();
        }
    }
}
